import os
import urllib3
import json
import notify

def login(callback, configs, context):
    http = urllib3.PoolManager()
    url = 'http://expadmin.superant.cc/login/actionlogin'
    headers = urllib3.util.make_headers(keep_alive=True,user_agent='Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6')

    params = {
        'username': 'tcy',
        'pwd': 'tcy123'
    }

    r = http.request('POST', url, params, headers)
    if r.status == 200:
        ret = r.data.decode('unicode_escape')
        if ret == '1':
            headers = r.getheaders()
            print(headers["Set-Cookie"])
            cookies = headers["Set-Cookie"]
            cookie = cookies[:cookies.find(";")]
            callback(cookie, configs, context)

def upload(cookie, configs, context):
    print("cookie " + cookie)
    boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW'
    headers = {
        'Accept-Charset': 'utf-8',
        "Accept": "*/*",
        'Content-Type': 'multipart/form-data;boundary=' + boundary,
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36",
        # "Cookie":"adminid=111; reqenv=local; webenv=1; isAdmin=1; username=tcy; chinesename=%E5%94%90%E8%8D%89%E5%8E%9F; sidlist=%5B1%2C2%5D;"
    }
    headers["Cookie"] = "adminid=111; reqenv=local; webenv=1; isAdmin=1; username=tcy; chinesename=%E5%94%90%E8%8D%89%E5%8E%9F; sidlist=%5B1%2C2%5D;" + cookie

    check = configs.copy()
    for config in configs:
        filename = os.path.basename(config)
        uploadName = filename.replace(".json", "")
        webhook = "http://expadmin.superant.cc/Debug/actionFileUpload/" + uploadName
        print("upload " + webhook)

        with open(config, 'r+', encoding='UTF-8') as freader:
            text = freader.read()

            http = urllib3.PoolManager()
            r = http.request(
                "POST",
                webhook,
                multipart_boundary = boundary,
                fields={
                    'file':(filename, text, 'text/plain')
                },
                headers=headers)

            if r.status == 200:
                print(r.data.decode('unicode_escape'))
                check.remove(config)

    if len(check) > 0:
        print("error: " + " ".join(check))
        context["Status"] = "Fail"
    else:
        print("success sync config " + str(len(configs)))
        context["Status"] = "Success"
    notify.push_result(context)

def deploy(configs, context):
    login(upload, configs, context)